﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using JCNT.DAL;
using Pub;
using System.IO;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Document;

namespace JCNT.NoteApp
{

    public partial class FMain : Form
    {
        CTreeII ctree = new CTreeII();
        string ID = "";
        string Tit = "";

        //语法高亮显示
        public string[] sItemName = new string[]{  
            "ASP/XHTML"    ,
            "BAT"          ,
            "Boo"          ,
            "Coco"         ,
            "C++.NET"      ,
            "C#"           ,
            "HTML"         ,
            "Java"         ,
            "JavaScript"   ,
            "Patch"        ,
            "PHP"          ,
            "TeX"          ,
            "VBNET"        ,
            "XML"          ,
            "TSQL"         ,
            "Python"       };

        const int CLOSE_SIZE = 15;                                              //tabPage标签图片
        Bitmap image;      //绘制“Ｘ”号即关闭按钮

        public List<FNode_Add> lstDoc = new List<FNode_Add>();   //窗口列表

        public FMain()
        {
            InitializeComponent();
        }

        private void FMain_Load(object sender, EventArgs e)
        {
            panel2.Dock = DockStyle.Fill;
            tabCtrlLeft.Dock = DockStyle.Fill;
            lboxTit.Dock = DockStyle.Fill;
            tabCtrl_Txt.Dock = DockStyle.Fill;
            tabCtrlLeft.SelectedIndex = 0;

            image = new Bitmap(Application.StartupPath + "\\exit.png");

            //清空控件
            this.tabCtrl_Txt.TabPages.Clear();
            //绘制的方式OwnerDrawFixed表示由窗体绘制大小也一样
            this.tabCtrl_Txt.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.tabCtrl_Txt.Padding = new System.Drawing.Point(CLOSE_SIZE, CLOSE_SIZE);
            //this.tabCtrl_Txt.DrawItem += new DrawItemEventHandler(this.tabCtrl_Txt_DrawItem);
            //this.tabCtrl_Txt.MouseDown += new System.Windows.Forms.MouseEventHandler(this.tabCtrl_Txt_MouseDown);

            tabCtrlFind.Visible = false;
            btnPic.Visible = false;
            btnBug.Visible = false;


            //CTextEditMenu richMenu = new CTextEditMenu(tboxCon);

            for (int i = 0; i < sItemName.Length; i++)
            {
                btnLaguage_Add(sItemName[i], 100 + i);
            }

            refTree();
        }

        public void btnLaguage_Add(string sText, int iTag)
        {
            ToolStripMenuItem m_Language = new ToolStripMenuItem();
            m_Language.Text = sText;
            m_Language.Tag = iTag;
            m_Language.Click += btn_Click;
            btnLanguage.DropDownItems.Add(m_Language);
        }

        public void btn_Click(object sender, EventArgs e)
        {
            int i_btn = 0;
            string content = "";
            if (sender is ToolStripMenuItem) i_btn = Convert.ToInt16(((ToolStripMenuItem)sender).Tag);
            if (sender is ToolStripButton) i_btn = Convert.ToInt16(((ToolStripButton)sender).Tag);
            if (sender is Button) i_btn = Convert.ToInt16(((Button)sender).Tag);
            if (sender is NotifyIcon) i_btn = Convert.ToInt16(((NotifyIcon)sender).Tag);
            if (sender is int) i_btn = Convert.ToInt16(sender);

            TreeNodeII node1 = (TreeNodeII)Program.ftree.tViewLab.SelectedNode;

            switch (i_btn)
            {
                case 1:     //Close
                    Close();
                    break;
                case 2:     //Picture Manage
                    Program.fpic.ShowDialog();
                    break;

                case 3:     //New
                    Program.fnodeAdd.EDT_STATE = 1;
                    Program.fnodeAdd.showVal(ID);
                    Program.fnodeAdd.Show();
                    //tboxCon.Visible = false;
                    tabCtrl_Txt.Visible = false;
                    break;

                case 4:     //edit
                    if (node1.typ == TreeNodeII.TYP_LAB)
                    {
                        Program.flabAdd.EDT_STATE = 2;
                        Program.flabAdd.showVal(node1);
                        Program.flabAdd.ShowDialog();
                        Program.fmain.Focus();
                        tabCtrl_Txt.Visible = false;
                    }
                    else if (node1.typ == TreeNodeII.TYP_TIT)
                    {
                        Program.fnodeAdd.EDT_STATE = 2;
                        Program.fnodeAdd.showVal(ID);
                        Program.fnodeAdd.Show();
                        tabCtrl_Txt.Visible = false;
                        //tboxCon.Visible = false;
                    }
  
                    break;
                case 5:     //delete

                    if (CPub.MsgBox("确定要删除[" + node1.Text + "]吗？", "删除") == true)
                    {
                        //删除标签
                        if (node1.typ == TreeNodeII.TYP_LAB) ctree.labDel(node1.ID);
                        //删除文章
                        else if (node1.typ == TreeNodeII.TYP_TIT) ctree.noteDel(node1.ID);

                        Program.ftree.tViewLab.SelectedNode.Remove();                       //删除树目录

                        for (int i = 0; i < lstDoc.Count;i++ )
                        {
                            if (node1.ID == lstDoc[i].ID)
                            {
                                lstDoc.RemoveAt(i);                    //删除窗口
                                this.tabCtrl_Txt.TabPages.RemoveAt(i);   //删除标签
                            }
                        }


                        refTree();
                    }
                    break;
                case 6:     //save
                    if (CPub.MsgBox("确定要保存吗？", "保存") == true)
                    {
                        Cwp_note wp_note = ctree.get_wp_note(ID);

                        int i_index = tabCtrl_Txt.SelectedIndex;
                        if (lstDoc[i_index].i_Typ_Pre == 0) wp_note.Con = lstDoc[i_index].tboxCon.Text;
                        else if (lstDoc[i_index].i_Typ_Pre == 1) wp_note.Con = lstDoc[i_index].tboxConII.Text;

                        ctree.noteEdt(wp_note);
                        //ctree.conEdt(ID, tboxCon);
                    }
                    break;
                case 7:     //refresh
                    refTree();
                    break;
                case 8:     //edit Tree Lable
                    panel1.Visible = !panel1.Visible;
                    break;
                case 9:     //Debug
                    Program.fdebug.ShowDialog();
                    break;
                case 10:    //About

                    break;
                case 11:    //find first
                    content = tboxFind.Text;
                    //CTextEditTool.FindFirst(this.tboxCon, content);

                    break;
                case 12:    //find prior
                    content = tboxFind.Text;
                    //CTextEditTool.FindText(this.tboxCon, content, RichTextBoxFinds.Reverse);
                    break;
                case 13:    //find next
                    content = tboxFind.Text;
                    //CTextEditTool.FindText(this.tboxCon, content, RichTextBoxFinds.None);
                    break;
                case 14:    //find end
                    content = tboxFind.Text;
                    //CTextEditTool.FindLast(this.tboxCon, content);
                    break;
                case 15:    //find text
                    tabCtrlFind.Visible = !tabCtrlFind.Visible;
                    break;
                case 16:    //close FindTextDialog
                    tabCtrlFind.Visible = false;
                    break;
                case 17:    //show Form
                    this.Show();
                    this.WindowState = FormWindowState.Normal;
                    this.Activate();
                    break;
                case 18:    //replace
                    int i_index2 = tabCtrl_Txt.SelectedIndex;
                    lstDoc[i_index2].tboxCon.Text = lstDoc[i_index2].tboxCon.Text.Replace(tboxOld.Text, tboxNew.Text);
                    break;
                case 20:
                case 21:
                case 22:
                    setView(i_btn - 20);
                    break; 
                case 100:
                case 101:
                case 102:
                case 103:
                case 104:
                case 105:
                case 106:
                case 107:
                case 108:
                case 109:
                case 110:
                case 111:
                case 112:
                case 113:
                case 114:
                case 115:
                    ToolStripMenuItem item = (ToolStripMenuItem)sender;
                    CDebug.Send(item.Text);
                    int i_index3 = tabCtrl_Txt.SelectedIndex;
                    lstDoc[i_index3].tboxCon.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy(item.Text);
                    lstDoc[i_index3].tboxCon.Encoding = System.Text.Encoding.Default;
                    break;
            }
        }

        private void refTree()
        {
            Program.ftree.ref_Tree();
            Program.ftree.ref_Tree2();
            ctree.fillLab(cboxLab);
        }

        private void cboxLab_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboxLab.SelectedItem == null) return;
            string ID = ((MyComboBoxItem)cboxLab.SelectedItem).Value;
            ctree.fillTit(lboxTit, ID);
        }

        private void lboxTit_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lboxTit.SelectedItem == null) return;
            string ID = ((MyComboBoxItem)lboxTit.SelectedItem).Value;
            fillRchText(ID);
        }

        /*
        public void fillRchText(string ID, RichTextBox tboxCon)
        {
            Cwp_note wp_note = ctree.get_wp_note(ID);
            if (wp_note == null)
            {
                labLab.Text = "[记录无法读取]";
                return;
            }
            this.ID = ID;
            this.Tit = wp_note.Tit;
            labID.Text = ID;
            labLab.Text = wp_note.Lab;
            labTit.Text = wp_note.Tit;
            labDat.Text = wp_note.SetDat;
            labLen.Text = wp_note.Con.Length.ToString();
            labOth.Text = wp_note.Oth;

            //显示代码视图
            setView(0);
            i_Typ_Pre = 0;

            tboxCon.Clear();

            try
            {
                if (wp_note.Dat == null)
                {
                    try
                    {
                        byte[] b = System.Text.Encoding.Default.GetBytes(wp_note.Con);
                        MemoryStream ms = new MemoryStream(b);
                        tboxCon.LoadFile(ms, RichTextBoxStreamType.RichText);
                        //ms.Close();
                    }
                    catch (System.Exception ex)
                    {
                        tboxCon.Text = wp_note.Con;
                    }

                }
                else
                {
                    MemoryStream ms = new MemoryStream(wp_note.Dat);

                    tboxCon.LoadFile(ms, RichTextBoxStreamType.RichText);
                    //ms.Close();
                }

            }
            catch
            {
                tboxCon.Text = wp_note.Con;
            }
        }
        */

        /// <summary>
        /// 显示文章内容
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="tboxCon"></param>
        public void fillRchText(string ID)
        {
            Cwp_note wp_note = ctree.get_wp_note(ID);
            if (wp_note == null)
            {
                labLab.Text = "[记录无法读取]";
                return;
            }
            this.ID = ID;
            this.Tit = wp_note.Tit;
            labID.Text = ID;
            labLab.Text = wp_note.Lab;
            labTit.Text = wp_note.Tit;
            labDat.Text = wp_note.SetDat;
            labLen.Text = wp_note.Con.Length.ToString();
            labOth.Text = wp_note.Oth;
            

            /*
            tboxCon.Text = "";
            tboxCon.Refresh();
#region 
            try
            {
                if (wp_note.Dat == null)
                {
                    try
                    {
                        byte[] b = System.Text.Encoding.Default.GetBytes(wp_note.Con);
                        MemoryStream ms = new MemoryStream(b);
                        tboxCon.LoadFile("", ms, true, true);
                        //ms.Close();
                    }
                    catch (System.Exception ex)
                    {
                        CDebug.SendError(ex.ToString());
                        CDebug.Send("填充文本框出错", ex);

                        tboxCon.Text = wp_note.Con;
                    }

                }
                else
                {
                    tboxCon.Text = wp_note.Con;
                }
            }
            catch (Exception ex2)
            {
                CDebug.SendError(ex2.ToString());
                CDebug.Send("填充文本框出错", ex2);

                tboxCon.Text = wp_note.Con;
            }
#endregion
            */
#region 创建标签
            Boolean b_creat = true;
            int i = 0;
            for (i = 0; i < lstDoc.Count; i++)
            {
                if (wp_note.Tit == lstDoc[i].Text)
                {
                    b_creat = false;
                    break;
                }
            }
            if (b_creat)
            {
                TabPage tabPage = new TabPage();
                tabPage.Text = wp_note.Tit;

                tabCtrl_Txt.TabPages.Add(tabPage);

                FNode_Add fdoc = new FNode_Add();
                fdoc.TopLevel = false;
                fdoc.Parent = tabPage;
                fdoc.Dock = DockStyle.Fill;
                fdoc.FormBorderStyle = FormBorderStyle.None;
                fdoc.panel1.Visible = false;        //隐藏标题及作者panel
                fdoc.splitter1.Visible = false;     //隐藏splitter
                fdoc.Show();

                fdoc.ID = ID;
                fdoc.Text = wp_note.Tit;
                fdoc.tboxCon.Text = wp_note.Con;

                lstDoc.Add(fdoc);

                tabCtrl_Txt.SelectedIndex = tabCtrl_Txt.TabPages.Count - 1;
            }
            else
            {
                tabCtrl_Txt.SelectedIndex = i;
            }
#endregion

            //显示代码视图
            setView(0);

        }


        private void tboxTit_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                string ID = "";
                if (cboxLab.SelectedItem != null)
                    ID = ((MyComboBoxItem)cboxLab.SelectedItem).Value;

                string key = tboxTit.Text;
                if (key == "") return;
                switch (key)
                {
                    case "show me the picture":
                        Program.fpic.Show();
                        tboxTit.Text = "";
                        break;
                    case "there is no spoon":
                        CTreeII.s_Vis = "";
                        refTree();
                        tboxTit.Clear();
                        break;
                    case "there is no magic":
                        CTreeII.s_Vis = "AND Vis = 1 ";
                        refTree();
                        tboxTit.Clear();
                        //tboxCon.Text = "";
                        break;
                    default:
                        ctree.fillTitII(lboxTit, key, ID);
                        break;
                }
            }
        }

        private void tboxCon_TextChanged(object sender, EventArgs e)
        {
            int i_index = tabCtrl_Txt.SelectedIndex;
            if (lstDoc[i_index].tboxCon.Focused)
                labLen.Text = lstDoc[i_index].tboxCon.Text.Length.ToString();
        }

        private void FMain_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void FMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            notifyIcon1.Icon.Dispose();
        }

        /// <summary>
        /// 切换不同视图、代码视图、文本视图、html视图
        /// </summary>
        /// <param name="i_Typ"></param>
        public void setView(int i_Typ)
        {
            string sTxt = "";
            int i_index = tabCtrl_Txt.SelectedIndex;
            if (lstDoc[i_index].i_Typ_Pre == 0) sTxt = lstDoc[i_index].tboxCon.Text;
            else if (lstDoc[i_index].i_Typ_Pre == 1) sTxt = lstDoc[i_index].tboxConII.Text;
            else if (lstDoc[i_index].i_Typ_Pre == 2) sTxt = lstDoc[i_index].webBrowCon.DocumentText;

            if (i_Typ == 0)
            {
                lstDoc[i_index].tboxCon.Visible = true;
                lstDoc[i_index].tboxConII.Visible = false;
                lstDoc[i_index].webBrowCon.Visible = false;

                lstDoc[i_index].tboxCon.Text = sTxt;
            }
            else if (i_Typ == 1)
            {
                lstDoc[i_index].tboxCon.Visible = false;
                lstDoc[i_index].tboxConII.Visible = true;
                lstDoc[i_index].webBrowCon.Visible = false;

                lstDoc[i_index].tboxConII.Text = sTxt;
            }
            else if (i_Typ == 2)
            {
                lstDoc[i_index].tboxCon.Visible = false;
                lstDoc[i_index].tboxConII.Visible = false;
                lstDoc[i_index].webBrowCon.Visible = true;

                lstDoc[i_index].webBrowCon.DocumentText = sTxt;
            }
            lstDoc[i_index].i_Typ_Pre = lstDoc[i_index].i_Typ;    //记录上次的文本框类型
            lstDoc[i_index].i_Typ = i_Typ;             //记录新的文本框类型

        }

        /// <summary>
        /// 绘制关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabCtrl_Txt_DrawItem(object sender, DrawItemEventArgs e)
        {
            try
            {
                Rectangle myTabRect = this.tabCtrl_Txt.GetTabRect(e.Index);

                //先添加TabPage属性   
                e.Graphics.DrawString(this.tabCtrl_Txt.TabPages[e.Index].Text,
                    this.Font, SystemBrushes.ControlText, myTabRect.X + 2, myTabRect.Y + 2);

                //再画一个矩形框
                using (Pen p = new Pen(Color.White))
                {
                    myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                    myTabRect.Width = CLOSE_SIZE;
                    myTabRect.Height = CLOSE_SIZE;
                    e.Graphics.DrawRectangle(p, myTabRect);
                }

                //填充矩形框
                Color recColor = e.State == DrawItemState.Selected ? Color.White : Color.White;
                using (Brush b = new SolidBrush(recColor))
                {
                    e.Graphics.FillRectangle(b, myTabRect);
                }

                //画关闭符号
                using (Pen objpen = new Pen(Color.Black))
                {
                    /*
                    //"\"线
                    Point p1 = new Point(myTabRect.X + 3, myTabRect.Y + 3);
                    Point p2 = new Point(myTabRect.X + myTabRect.Width - 3, myTabRect.Y + myTabRect.Height - 3);
                    e.Graphics.DrawLine(objpen, p1, p2);

                    //"/"线
                    Point p3 = new Point(myTabRect.X + 3, myTabRect.Y + myTabRect.Height - 3);
                    Point p4 = new Point(myTabRect.X + myTabRect.Width - 3, myTabRect.Y + 3);
                    e.Graphics.DrawLine(objpen, p3, p4);
                    */

                    ////=============================================
                    Bitmap bt = new Bitmap(image);
                    Point p5 = new Point(myTabRect.X, 4);
                    e.Graphics.DrawImage(bt, p5);
                    //e.Graphics.DrawString(this.tabCtrl_Txt.TabPages[e.Index].Text, this.Font, objpen.Brush, p5);

                }


                //绘制小图标              
                //==============================================================================
                //Bitmap bt = new Bitmap("E:\\1\\2.jpg");
                //Point p5 = new Point(4, 4);
                ////e.Graphics.DrawImage(bt, e.Bounds);
                //e.Graphics.DrawImage(bt, p5);
                //Pen pt = new Pen(Color.Red);
                ////e.Graphics.DrawString(this.tabCtrl_Txt.TabPages[e.Index].Text, this.Font, pt.Brush, e.Bounds);
                //e.Graphics.DrawString(this.tabCtrl_Txt.TabPages[e.Index].Text, this.Font, pt.Brush, p5);

                e.Graphics.Dispose();
            }
            catch (Exception)
            {

            }
        }

        //关闭按钮功能
        private void tabCtrl_Txt_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                int x = e.X, y = e.Y;

                //计算关闭区域   
                Rectangle myTabRect = this.tabCtrl_Txt.GetTabRect(this.tabCtrl_Txt.SelectedIndex);

                myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                myTabRect.Width = CLOSE_SIZE;
                myTabRect.Height = CLOSE_SIZE;

                //如果鼠标在区域内就关闭选项卡   
                bool isClose = x > myTabRect.X && x < myTabRect.Right
                 && y > myTabRect.Y && y < myTabRect.Bottom;

                if (isClose == true)
                {
                    lstDoc.RemoveAt(this.tabCtrl_Txt.SelectedIndex);
                    this.tabCtrl_Txt.TabPages.Remove(this.tabCtrl_Txt.SelectedTab);
                }
            }
        }

    }
}
